package com.ly.video.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

// 处理Token
public class TokenUtil {

    /**
     * 默认为10天的token
     */
    public static String getToken(String uid, String sign){
        String token;
        token= JWT.create().withClaim("uid",uid)
                .withClaim("generatetime",System.currentTimeMillis())
                .withClaim("exptime", 1000 * 60 * 60 * 24 * 30)//设置token过期时间为30天
                .sign(Algorithm.HMAC256(sign));
        return token;
    }


    /**
     * 自定义有效时长的token
     */
    public static String createToken(String uid,String account,Long liveTime){
        String token;
        token= JWT.create().withClaim("uid",uid)
                .withClaim("generatetime",System.currentTimeMillis())
                .withClaim("exptime",liveTime)
                .sign(Algorithm.HMAC256(account));
        return token;
    }

    /**
     * 返回参数
     * true：toke有效
     * false：token无效
     */
    public static boolean decodeToken(String token){
        Long currentTime = System.currentTimeMillis();
        try {
            Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
            Long expTime = JWT.decode(token).getClaim("exptime").asLong();
            if (currentTime - generateTime > expTime) {
                return false;
            }
            else return true;
        }catch (Exception e){
            return true;
        }
    }
}
